from functools import wraps

from flask import current_app, request, g

from .operation_trajectory_model import OperationTrajectory

def and_operation_trajectory(func):
    @wraps(func)
    def wrap(document):
        # ip
        ip = request.remote_addr
        try:
            _ip = request.headers["X-Real-IP"]
            if _ip is not None:
                ip = _ip
        except Exception as e:
            pass
        need_record_model = current_app.config.get('NEED_RECORD_MODEL')
        need_record_main_field = current_app.config.get(
            'NEED_RECORD_MAIN_FIELD')
        model_name = document.__class__.__name__
        if model_name in need_record_model:
            index = need_record_model.index(model_name)
            res = func(document)
            func_name = func.__name__
            if func_name == 'to_delete':
                page = '删除' + document._meta['verbose_name']
                detail = page + ':' + \
                    getattr(document, need_record_main_field[index])
            if func_name == 'to_new':
                page = '新建' + document._meta['verbose_name']
                detail = page + ':' + \
                    getattr(res, need_record_main_field[index])
            if func_name == 'to_update':
                page = '编辑' + document._meta['verbose_name']
                detail = page + ':' + \
                    getattr(document, need_record_main_field[index])
            OperationTrajectory(ip=ip, page=page, detail=detail, opetation_user=g.opetation_user,
                                project=g.operation_trajectory_project).save()
        return res
    return wrap
